package com.aliengen.thingple.driverapp.ui.activities;

import android.content.Intent;
import android.content.res.Resources;
import android.util.Log;
import android.widget.TextView;

import com.aliengen.thingple.beep.DevBeep;
import com.aliengen.thingple.driverapp.R;
import com.aliengen.thingple.driverapp.data.local.ProductModel;
import com.aliengen.thingple.driverapp.network.api.ThingpleAPI;
import com.aliengen.thingple.driverapp.network.api.exception.APICallException;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.List;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@EActivity(R.layout.activity_loading)
public class LoadingActivity extends AbstractBaseActivity {

    @ViewById
    TextView loadingStatus;

    Boolean isServiceRunning = false;

    protected void setLoadingStatus(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingStatus.setText(message);
                loadingStatus.invalidate();
            }
        });
    }

    @AfterViews
    void init() {
        isServiceRunning = false;

        Thread thread = new Thread() {

            @Override
            public void run() {

                Resources res = getResources();
                try {
                    super.run();
                    Integer tryRestart = 0;
                    while (!isServiceRunning) {
                        String text;
                        if (mApplication.mService == null || !mApplication.bBind) {
                            text = res.getString(R.string.loading_state_not_running);
                        }
                        else
                        if (mApplication.mService.device == null) {
                            text = res.getString(R.string.loading_state_not_detected);
                        }
                        else
                        if (mApplication.mService.device.getDeviceIsOpen()) {
                            text = res.getString(R.string.loading_state_ready);
                            isServiceRunning = true;
                        }
                        else {
                            if(tryRestart > 0)
                            {
                                tryRestart--;
                                mApplication.restartService();
                                text = res.getString(R.string.loading_state_retry);
                            }
                            else
                            {
                                text = res.getString(R.string.loading_state_not_available);
                                System.out.println("mApplication.mService.device.getDeviceIsOpen() return false...");
                                mApplication.killService();
                                //android.os.Process.killProcess(android.os.Process.myPid());
                            }
                        }

                        LoadingActivity.this.setLoadingStatus(text);
                        try {
                            synchronized (this) {
                                wait(2000);
                            }
                        } catch (InterruptedException ex) {
                            Log.e("error_ie", ex.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Log.e("error", e.getMessage());
                } finally {
                    DevBeep.PlayOK();
                    Intent i = new Intent(LoadingActivity.this, TruckActivity_.class);
                    startActivity(i);
                    finish();
                }
            }
        };

        thread.start();
        try {
            mApplication.api.retrieveProducts(new ThingpleAPI.Listener<List<ProductModel>>() {
                @Override
                public void onResponse(List<ProductModel> object) {
                    showToast(object.size() + " product(s) retrieved!");
                }

                @Override
                public void onError(String message) {
                    showToast("Product sync need to be done soon!");
                }
            });
        }catch(APICallException e)
        {
            Log.e("LoadingActivity", e.getMessage());
        }
    }
}
